<template>
  <view class="index">
    <view class="userInfo">
      <view class="logo"></view>
      <view class="desc">皖影随行运营平台</view>
    </view>
    <view class="loginBox">
      <view class="loginItem">
        <view class="icon icon_phone"></view>
        <view class="content">
          <nut-input v-model="userInfo.username" placeholder="请输入用户名"  :border="false" />
        </view>
      </view>
      <view class="loginItem">
        <view class="icon icon_lock"></view>
        <view class="content">
          <nut-input v-model="userInfo.password" type="password" placeholder="请输入密码" :border="false" />
        </view>
      </view>
    </view>
    <view class="loginBtn">
      <nut-button type="success" block color="linear-gradient(to right, #ff6034, #ee0a24)" @click="userLogin">登录</nut-button>
    </view>
    <nut-toast :msg="state.msg" v-model:visible="state.show" :type="state.type" @closed="onClosed" :cover="state.cover" />

  </view>
</template>

<script setup>
import './index.scss';
import { reactive, ref } from 'vue';
import { IconFont } from '@nutui/icons-vue-taro'
import { My } from '@nutui/icons-vue-taro'
import { login, getPublicKey } from '../../https/api';
import JSEncrypt from 'jsencrypt';
import Taro from '@tarojs/taro';
const userInfo = reactive({
  username: '',
  password: '',
  private_key_id: ''
})
const state = reactive({
  msg: 'toast',
  type: 'text',
  show: false,
  cover: false,
  title: '',
  bottom: '',
  center: true
})
const encryptWithPublicKey = (data, publicKey) => {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(data);
}
const userLogin = () => {
  if (!userInfo.username) {
    state.show = true
    state.type = 'fail'
    state.msg = '用户名不能为空'
    return
  }
  if (!userInfo.password) {
    state.show = true
    state.type = 'fail'
    state.msg = '密码不能为空'
    return
  }
  getPublicKey().then(res => {
      userInfo.private_key_id = res.data.private_key_id
      login({
          username: encryptWithPublicKey(userInfo.username, res.data.public),
          password: encryptWithPublicKey(userInfo.password, res.data.public),
          private_key_id: userInfo.private_key_id
      }).then(reslute => {
          if(reslute.code == '1000') {
            Taro.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
            Taro.setStorage({
              key:"userInfo",
              data:JSON.stringify(reslute.data)
            })
            Taro.setStorage({
              key:"token",
              data: reslute.data.token_key
            })
            Taro.reLaunch({
              url: '/pages/centpage/index'
            })
          } else {
            Taro.showToast({
              title: reslute.msg,
              icon: 'none',
              duration: 2000
            })
          }
      })
  })
}
const onClosed = () => console.log('closed')

</script>

<style>
</style>